//
//  GYJournal.m
//  LockManagement
//
//  Created by apple on 2018/8/20.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYJournal.h"
#import "GYNetWorkTools.h"
#import "GYJournal+GYWCTTableCoding.h"
#import "NSString+GYPath.h"
#import <WCDB/WCDB.h>

@implementation GYJournal

+ (void)getJournalList:(NSString *)beginTime endTime:(NSString *)endTime current:(NSString *)current pageSize:(NSString *)pageSize success:(void (^)(NSArray *, NSInteger))success error:(void (^)(NSError *))failed {
    NSMutableArray *tempArray = [NSMutableArray array];
    NSString *IP = GETOBJ(@"IP")
    NSString *port = GETOBJ(@"port")
    [SVProgressHUD showWithStatus:@"正在加载日志列表..."];
    [GYNetWorkTools requestLogListsWithURL:[NSString stringWithFormat:@"http://%@:%@/api/logsList",IP,port] logStart:beginTime logEnd:endTime current:current pageSize:pageSize success:^(NSDictionary *obj) {
        //NSLog(@"obj========%@",obj);
        [SVProgressHUD dismiss];
        int state = [[obj objectForKey:@"state"] intValue];
        if (state == 0) {
            NSArray *data = [obj objectForKey:@"data"];
            for (NSDictionary *dic in data) {
                GYJournal *model = [[GYJournal alloc] initWithDic:dic];
                model.currentDate = [[beginTime componentsSeparatedByString:@" "] firstObject];
                [tempArray addObject:[[GYJournal alloc] initWithDic:dic]];
            }
            NSDictionary *pageInfo = [obj objectForKey:@"pageInfo"];
            NSInteger totalItems = [[pageInfo objectForKey:@"totalItems"] integerValue];
            success(tempArray, totalItems);
            
            //使用异步线程把数据缓存到数据库
//            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                BOOL successed = [self createJournalTable];
//                for (GYJournal *journal in tempArray) {
//                    if (successed) {
//                        [self insertJournal:journal];
//                    }
//                }
//            });
            
        }else {
            //加载日志失败,获取数据库中的数据
            NSArray *journals = [self getAllJournalData:[[beginTime componentsSeparatedByString:@" "] firstObject]];
            success(journals,INT_MAX); //如果网络加载我们传递总数 是最大的int数  以便后面有网络时候可以正常加载
            //[SVProgressHUD showErrorWithStatus:@"加载日志列表失败"];
        }
    } error:^(NSError *error) {
        //加载日志失败,获取数据库中的数据
        NSArray *journals = [self getAllJournalData:[[beginTime componentsSeparatedByString:@" "] firstObject]];
        success(journals,INT_MAX);
        failed(error);
        [SVProgressHUD showErrorWithStatus:@"加载日志列表失败"];
        NSLog(@"log list=======%@",error);
    }];
}

- (instancetype)initWithDic:(NSDictionary *)dic {
    self = [super init];
    if (self) {
        [self setValuesForKeysWithDictionary:dic];
    }
    
    return self;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    
}

#pragma mark -- WCDB 数据库操作

// 利用这个宏定义绑定到表的类
//WCDB_IMPLEMENTATION(GYJournal)
WCDB_IMPLEMENTATION(GYJournal)

// 下面四个宏定义绑定到表中的字段
WCDB_SYNTHESIZE(GYJournal, logID)
WCDB_SYNTHESIZE(GYJournal, logTime)
WCDB_SYNTHESIZE(GYJournal, logType)
WCDB_SYNTHESIZE(GYJournal, userID)
WCDB_SYNTHESIZE(GYJournal, userName)
WCDB_SYNTHESIZE(GYJournal, keyID)
WCDB_SYNTHESIZE(GYJournal, keyName)
WCDB_SYNTHESIZE(GYJournal, lockID)
WCDB_SYNTHESIZE(GYJournal, lockName)
WCDB_SYNTHESIZE(GYJournal, logState)
WCDB_SYNTHESIZE(GYJournal, upTime);
WCDB_SYNTHESIZE(GYJournal, currentDate)

// 约束宏定义数据库的主键
WCDB_PRIMARY(GYJournal, logID)

// 定义数据库的索引属性，它直接定义createTime字段为索引
// 同时 WCDB 会将表名 + "_index" 作为该索引的名称
//WCDB_INDEX(Message, "_index", createTime)

+ (BOOL)createJournalTable {
    WCTDatabase *database = [self createDataBase];
    
    BOOL result = [database createTableAndIndexesOfName:@"journal"
                                              withClass:GYJournal.class];
    return result;
}

+ (void)insertJournal:(GYJournal *)journal {
    WCTDatabase *database = [self createDataBase];
    [database insertObject:journal into:@"journal"];
}

+ (NSArray<GYJournal *> *)getAllJournalData:(NSString *)condition {
    WCTDatabase *database = [self createDataBase];
    NSArray<GYJournal *> * journal = [database getObjectsOfClass:GYJournal.class fromTable:@"journal" orderBy:GYJournal.logID.order()];
    
    NSMutableArray *array = [NSMutableArray array];
    for (GYJournal *model in journal) {
        if ([model.currentDate isEqualToString:condition]) {
            [array addObject:model];
        }
    }
    
    return array ;
}

+ (WCTDatabase *)createDataBase {
    // 文件路径
    NSString *filePath = [NSString DocumentDir:@"journal.sqlite"];
    
    WCTDatabase *database = [[WCTDatabase alloc] initWithPath:filePath];
    
    return database;
}
@end
